package com.zhanqiao.controller;

import com.alibaba.fastjson.JSON;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zhanqiao.domain.UserBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/checkuser")
public class CheckUserContorller extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        DataSource ds = new ComboPooledDataSource();
        QueryRunner queryRunner = new QueryRunner(ds);
        resp.setContentType("application/json;charset=utf8");
        Map map =new HashMap();
        try {
            List execute = queryRunner.execute("select * from user where uname = '" + username + "'", new BeanHandler(UserBean.class));            if(execute.get(0)==null){
                map.put("message","该用户可以使用!");
            }else{
                map.put("message","该用户已存在!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String json = JSON.toJSONString(map);
        resp.getWriter().write(json);
    }
}
